<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>谷歌SOE--台湾股票推荐资讯</title>

  <style>
    .edit-text {
      color: orange;
      cursor: pointer;
    }

    body {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif;
      background-color: #f5f5f5;
    }

    header {
      background-color: #4285f4;
      color: #ffffff;
      padding: 20px;
      text-align: center;
      font-size: 24px;
    }

    .top {
      text-align: center;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      max-width: 1080px;
      margin: auto;
      padding: 20px;
    }

    .top .card {
      width: 200px;
      height: 90px;

      margin-right: 15px;
      padding: 20px;
    }

    canvas {
      display: block;
      margin: 50px auto;
    }

    .container {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      max-width: 1080px;
      margin: auto;
      padding: 20px;
    }

    .down {
      max-width: 1080px;
      margin: 0 auto;
      padding: 20px;
    }

    .card {
      background-color: #ffffff;
      border-radius: 10px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      padding: 20px;
      margin-bottom: 20px;
    }

    .card h2 {
      font-size: 20px;
      margin-top: 0;
    }

    .card p {
      font-size: 18px;
      margin-bottom: 10px;
    }

    .chart {
      width: 100%;
      height: 300px;
      margin-bottom: 20px;
    }

    .chart canvas {
      width: 100%;
      height: 100%;
    }

    .pie-chart-legend {
      list-style: none;
      margin: 0;
      padding: 0;
      font-size: 16px;
    }

    .pie-chart-legend li {
      margin-bottom: 10px;
    }

    .pie-chart-legend li span {
      display: inline-block;
      width: 20px;
      height: 20px;
      margin-right: 10px;
      border-radius: 50%;
    }

    .pie-chart-legend li span.region-1 {
      background-color: #4285f4;
    }

    .pie-chart-legend li span.region-2 {
      background-color: #34a853;
    }

    .pie-chart-legend li span.region-3 {
      background-color: #fbbc05;
    }

    .pie-chart-legend li span.region-4 {
      background-color: #ea4335;
    }

    /* 表格样式 */
    table {
      width: 300px;
      border-collapse: collapse;
      font-size: 14px;
      /* width: 100%;
        height: 200px;
        margin-bottom: 20px; */
    }

    th,
    td {
      text-align: center;
      padding: 8px;
    }

    /* 行间隔 */
    tr:nth-child(even) {
      background-color: #f2f2f2;
    }

    /* 鼠标悬停效果 */
    tr:hover {
      background-color: #ddd;
    }
  </style>
</head>

<body>
  <div id="app">
    <header>
      <h1>谷歌SOE--台湾股票推荐资讯</h1>
    </header>

    <div class="top" style="text-align: center">
      <div class="card">
        <h2>{{topData.userBalanceLabel}}</h2>
        <p>{{topData.userBalanceVal}}</p>
      </div>
      <div class="card">
        <h2>{{topData.remainingBalanceLabel}}</h2>
        <p>{{topData.remainingBalanceVal}}</p>
      </div>
      <div class="card">
        <h2>{{topData.webClickCountLabel}}</h2>
        <p>{{topData.webClickCountVal}}</p>
      </div>
      <div class="card">
        <h2>{{topData.clickCostLabel}}</h2>
        <p>{{topData.clickCostVal}}</p>
      </div>
      <div class="card">
        <h2>{{topData.clickCountLabel}}</h2>
        <p>{{topData.clickCountVal}}</p>
      </div>

    </div>


    <div class="container">
      <div class="card">
        <h2>转化百分比</h2>
        <div class="myCanvas" style="text-align: center;">

          <canvas id="myCanvas" width="200" height="200"></canvas>
          <p>总转化率</p>
          <p>转化率：{{topData.averageTransactionPrice}}</p>
        </div>

      </div>
      <div class="card">
        <h2>访问前十国家</h2>
        <div class="chart">
          <table id="myTable"></table>
        </div>
      </div>
      <div class="card">
        <h2>访问国家前十占比</h2>
        <div class="chart">
          <canvas id="pie-chart"></canvas>
        </div>
      </div>
    </div>
    <div class="down">
      <h2>消费余额明细</h2>
      <div class="card">
        <div id="appx">
          <el-table :data="tableData" class="tableData">
            <el-table-column prop="category" label="消费类别"></el-table-column>
            <el-table-column prop="amount" label="消费金额" sortable></el-table-column>
            <el-table-column prop="time" label="时间" sortable>
              <template slot-scope="scope">
               {{getFormtTime(scope.row.time)}}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" sortable></el-table-column>
            <el-table-column prop="paymentMethod" label="支付方式"></el-table-column>
            <el-table-column prop="account" label="存款账户"></el-table-column>
          </el-table>


          <el-dialog title="编辑消费记录" :visible.sync="dialogVisible">
            <el-form :model="editedItem">
              <el-form-item label="消费类别">
                <el-input v-model="editedItem.category"></el-input>
              </el-form-item>
              <el-form-item label="消费金额">
                <el-input-number v-model="editedItem.amount" controls-position="right"></el-input-number>
              </el-form-item>
              <el-form-item label="时间">
                <el-date-picker v-model="editedItem.time" type="date" value-format="timestamp" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="数量">
                <el-input-number v-model="editedItem.quantity" controls-position="right"></el-input-number>
              </el-form-item>
              <el-form-item label="支付方式">
                <el-input v-model="editedItem.paymentMethod"></el-input>
              </el-form-item>
              <el-form-item label="存款账户">
                <el-input v-model="editedItem.account"></el-input>

              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveEdit">保存</el-button>
            </span>
          </el-dialog>


          <el-dialog title="添加消费记录" :visible.sync="addDialogVisible" width="30%">
            <el-form :model="newRow" label-width="120px">
              <el-form-item label="消费类别">
                <el-input v-model="newRow.category"></el-input>
              </el-form-item>
              <el-form-item label="消费金额">
                <el-input-number v-model="newRow.amount" controls-position="right"></el-input-number>
              </el-form-item>
              <el-form-item label="时间">
                <el-date-picker v-model="newRow.time" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="数量">
                <el-input-number v-model="newRow.quantity" controls-position="right"></el-input-number>
              </el-form-item>
              <el-form-item label="支付方式">
                <el-input v-model="newRow.paymentMethod"></el-input>
              </el-form-item>
              <el-form-item label="存款账户">
                <el-input v-model="newRow.account"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitNewRow">添加</el-button>
            </span>
          </el-dialog>

        </div>
      </div>
    </div>
  </div>
  <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
  <script src="https://unpkg.com/element-ui@2.15.6/lib/index.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
  <script>


    new Vue({
      el: '#app',
      data() {
        return {
          tableData: [],
          dialogVisible: false,
          editedItem: {},
          addDialogVisible: false,
          newRow: {},
          topData: {},
        };
      },
      mounted() {
        this.getTopData();
        this.$nextTick(() => {
          this.init()
        })
      },
      created() {
        this.fetchData();
      },
      methods: {
        //中间数据为今日销售总额 todayTotalSales
        //圆形进度条百分比=今日总销售额 todayTotalSales /网站点击量 webClickCountVal
        init() {
          $.getJSON("/data.json", function (data) {
            var ctx = document.getElementById('pie-chart').getContext('2d');
            var labelsArr = [];
            var dataArr = [];
            data.forEach(function (item) {
              labelsArr.push(item.region)
              dataArr.push(item.score)
            })
            var myChart = new Chart(ctx, {
              type: 'pie',
              data: {
                labels: ['Region 1', 'Region 2', 'Region 3', 'Region 4'],
                labels: labelsArr,
                datasets: [{
                  data: dataArr,
                  // data: [data.region1, data.region2, data.region3, data.region4],
                  backgroundColor: ["#4285f4", "#34a853", "#fbbc05", "#ea4335", "#5f6368", "#ea9999", "#f3722c", "#6ab04c", "#f9c74f", "#f8961e"],

                  // backgroundColor: [
                  //   'rgba(255, 99, 132, 0.2)',
                  //   'rgba(54, 162, 235, 0.2)',
                  //   'rgba(255, 206, 86, 0.2)',
                  //   'rgba(75, 192, 192, 0.2)'
                  // ],
                  // borderColor: [
                  //   'rgba(255, 99, 132, 1)',
                  //   'rgba(54, 162, 235, 1)',
                  //   'rgba(255, 206, 86, 1)',
                  //   'rgba(75, 192, 192, 1)'
                  // ],
                  borderWidth: 1
                }]
              },
              options: {
                responsive: true,
                maintainAspectRatio: false
              }
            });
          });

          // 从本地 JSON 文件中获取数据
          fetch('/data.json')
            .then(response => response.json())
            .then(data => {
              // 按分数从大到小排名
              data.sort((a, b) => b.score - a.score);

              // 将数据添加到列表中
              // const myList = document.getElementById('myList');
              // myList.innerHTML = '';

              // data.forEach(item => {
              //   const li = document.createElement('li');
              //   li.textContent = `${item.region}: ${item.score}`;
              //   myList.appendChild(li);
              // });
            });

          // 使用 AJAX 获取 data.json 文件中的数据
          let xhr = new XMLHttpRequest();
          xhr.open('GET', 'data.json', true);
          xhr.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
              // 将 JSON 数据解析为 JavaScript 对象
              const data = JSON.parse(this.responseText);

              // 按分数从高到低进行排序
              data.sort((a, b) => b.score - a.score);

              // 生成表格内容
              let tableContent = '';
              for (let i = 0; i < data.length; i++) {
                tableContent += '<tr>';
                tableContent += `<td>${i + 1}</td>`;
                tableContent += `<td>${data[i].region}</td>`;
                tableContent += `<td>${data[i].score}</td>`;
                tableContent += '</tr>';
              }

              // 将表格内容添加到表格中
              document.getElementById('myTable').innerHTML = tableContent;
            }
          };
          xhr.send();
        },
        async fetchData() {
          try {
            let response = await fetch('list4.json');
            let data = await response.json();
            this.$nextTick(() => {
              console.log('----tableData---', data)
              this.$set(this, 'tableData', data);
            })

            // this.tableData = data;
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        },
        getTopData() {
          let _this = this;
          fetch("top.json").then(function (res) {
            return res.json()
          }).then(function (data) {
            _this.$set(_this, 'topData', data);
            //渲染canvas
            console.log(_this.topData, _this.topData.todayTotalSales, _this.topData.webClickCountVal);
            let radio = (Number(_this.topData.todayTotalSales) / Number(_this.topData.webClickCountVal)) * 100
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            var x = canvas.width / 2;
            var y = canvas.height / 2;
            var radius = 80;
            var lineWidth = 10;
            var percent = radio; // 进度条百分比，可根据需要修改
            var font_size = 20; // 字体大小
            var text;

            function drawCircle(x, y, radius, lineWidth, percent, color) {
              context.beginPath();
              context.arc(x, y, radius, 0, Math.PI * 2, false);
              context.strokeStyle = "#ccc";
              context.lineWidth = lineWidth;
              context.stroke();

              context.beginPath();
              context.arc(x, y, radius, Math.PI * 2 * percent / 100 - Math.PI / 2, -Math.PI / 2, true); // 反方向
              context.strokeStyle = color;
              context.lineWidth = lineWidth;
              context.lineCap = "round"; // 添加圆角美化
              context.stroke();

              context.font = font_size + "px Arial";
              context.fillStyle = color;
              context.textAlign = "center";
              context.textBaseline = "middle";
              text = _this.topData.todayTotalSales; //今日销售总额
              context.fillText(text, x, y);
            }
            drawCircle(x, y, radius, lineWidth, percent, "#ffa500"); // 修改为橙色
          }).catch(function (e) {
            console.error(e)
          })
        },
        submitNewRow() {
          this.tableData.push({ ...this.newRow });
          this.addDialogVisible = false;
          this.resetNewRow();
        },
        resetNewRow() {
          this.newRow = {
            category: "",
            amount: 0,
            time: "",
            quantity: 1,
            paymentMethod: "",
            account: ""
          };
        },

        editRow(row) {
          this.editedItem = Object.assign({}, row);
          this.dialogVisible = true;
        },
        saveEdit() {
          const index = this.tableData.findIndex(item => item === this.editedItem);
          if (index > -1) {
            this.tableData.splice(index, 1, this.editedItem);
          }
          this.dialogVisible = false;
        },
	  //dateTime：时间戳；  flag：取值为true/false，用于判断是否需要显示时分秒
    getFormtTime(dateTime,flag) {
    	if(dateTime != null ) {
    		//若传入的dateTime为字符串类型，需要进行转换成数值，若不是无需下面注释代码
    		//var time = parseInt(dateTime)
    		var date = new Date(dateTime);
    		//获取年份
    		var YY = date.getFullYear();
    		//获取月份
    		var MM = (date.getMonth() + 1 < 10 ? '0'+(date.getMonth() + 1) : date.getMonth() + 1);
    		//获取日期
    		var DD = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate());
    		if(flag) { //flag为true，显示时分秒格式
    			//获取小时
    			var hh = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours());
    			//获取分
    			var mm = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes());
    			///获取秒
    			var ss = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
    			//返回时间格式： 2020-11-09 13:14:52
    			return YY + '-' + MM + '-' + DD + ' ' + hh + ':' + mm + ':' + ss;
    		} else {
    			//返回时间格式： 2020-11-09
    			return YY + '-' + MM + '-' + DD;
    		}
    	} else {
    		return "";
    	}
    }

      }
    });
  </script>
</body>

</html>